from rest_framework.response import Response
from rest_framework.status import HTTP_504_GATEWAY_TIMEOUT
from rest_framework_jwt.authentication import jwt_decode_handler
from six_it.models import Question
from six_it.serializers.question import QuestionSerializers
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView,GenericAPIView
from rest_framework.mixins import RetrieveModelMixin,CreateModelMixin,DestroyModelMixin

from six_it.models import Question, Reply, Comment, User
from six_it.serializers.reply import ReplySerializer


class ReplyAPIView(APIView):
    def post(self,request):
        request.data['user'] = request.user.id
        rep = ReplySerializer(data=request.data)
        rep.is_valid()
        rep.save()
        rep = Question.objects.get(id=request.data['problem'])
        rep.reply += 1
        rep.save()
        return Response({'message':'ok',"success": True})
class ReplyYesAPIView(APIView):
    def put(self,request,id):
        try:
            token = self.request.auth
            toke_user = jwt_decode_handler(token)
            user_id = toke_user["user_id"]
        except Exception as e:
            return Response('请先登录', status=404)
        try:
            question = Reply.objects.get(id=id)
        except Exception as e:
            return Response(status=HTTP_504_GATEWAY_TIMEOUT)
        question.useful_count += 1
        question.save()
        return Response({'message':'谢谢支持',"success": True})
class ReplyNoAPIView(APIView):

    def put(self,request,id):
        try:
            token = self.request.auth
            toke_user = jwt_decode_handler(token)
            user_id = toke_user["user_id"]
        except Exception as e:
            return Response('请先登录', status=404)
        try:
            question = Reply.objects.get(id=id)
        except Exception as e:
            return Response(status=HTTP_504_GATEWAY_TIMEOUT)
        if question.useful_count != 0:
            question.useful_count -= 1
        question.unuseful_count += 1
        question.save()
        return Response({'message':'下次加油',"success": True})
